<template>
	<view>
		<slot name="default" :timeStatus="timeStatus">
			<!-- 默认的插槽内容 -->
			<view class="xl-count-down" :style="{'--time-size': $xl.parseUnit(timeSize, 'rpx'),'--cart-size': $xl.parseUnit(cartSize, 'rpx')}">
				<view v-if="timeType == 'cart'" class="cart">
					<view v-for="(item, index) in timeStatus.formatTime.match(/\d+|[^0-9]+/g)" :key="index" :class="[index %2 == 0 ? 'num':'split']">
						{{item}}
					</view>
				</view>
				<view v-else class="time">{{ timeStatus.formatTime }}</view>
				<view v-if="showStatus" class="status" :style="{fontSize: $xl.parseUnit(statusSize, 'rpx')}">{{ timeStatus.status }}</view>
			</view>
		</slot>
	</view>
</template>

<script setup>
	import { ref, watch, onUnmounted } from 'vue';
	import propsData from './props.js'
	const props = defineProps(propsData)

	const emits = defineEmits(['update:status']);

	let timeoutId;
	// 创建响应式引用
	const timeStatus = ref({
		started: false,
		ended: false,
		remain: 0,  // 剩余时间毫秒
		days: 0,
		hours: 0,
		minutes: 0,
		seconds: 0,
		milliseconds: 0,
		formatTime: '',
		status: props.name + '未开始'
	});
	
	// 监听 props 变化
	watch(() => [props.startTime, props.endTime], () => {
		calculateTimeStatus();
	}, {immediate: true});

	// 计算时间状态的函数
	function calculateTimeStatus() {
		const now = new Date();
		const start = new Date(props.startTime);
		const end = new Date(props.endTime);
		const started = now >= start;
		const ended = now >= end;

		let status = started && !ended;

		// 发射自定义事件，传递状态值给父组件
		emits('update:status', status);
		
		if (ended){
			timeStatus.value = {
				started,
				ended,
				remain: 0,
				days: 0,
				hours: 0,
				minutes: 0,
				seconds: 0,
				milliseconds: 0,
				formatTime: props.format.replace("dd", "00").replace("HH", "00").replace("mm", "00").replace("ss", "00").replace("SSS", "000"),
				status: props.name + '已结束'
			};
		}else{
			if (started) timeStatus.value = formatRemainTime(end - now, "进行中")
			else timeStatus.value = formatRemainTime(start - now, "未开始")
			timeoutId = setTimeout(()=>{
				calculateTimeStatus()
			}, props.format.indexOf("SSS") !== -1 ? 60:1000)
		} 
	}

	// 格式化剩余时间
	function formatRemainTime(ms, status) {
		if (ms < 0) return "";
		// 若要显示毫秒
		let SSS = 0;
		if(props.format.indexOf("SSS") !== -1) SSS = ms % 1000; // 毫秒
		const totalSeconds = Math.floor(ms / 1000);
		const ss = totalSeconds % 60; // 秒
		const totalMinutes = Math.floor(totalSeconds / 60);
		const mm = totalMinutes % 60; // 分钟
		let HH = Math.floor(totalMinutes / 60); // totalHours
		let dd = 0;
		// 若要显示天
		if(props.format.indexOf("dd") !== -1) {
			dd = Math.floor(HH / 24); // 天数
			HH = HH % 24; // 小时
		}
		
		// 使用正则替换格式中的时间部分
		const formatTime = props.format
		    .replace("dd", dd.toString().padStart(2, "0"))
		    .replace("HH", HH.toString().padStart(2, "0"))
		    .replace("mm", mm.toString().padStart(2, "0"))
		    .replace("ss", ss.toString().padStart(2, "0"))
		    .replace("SSS", SSS.toString().padStart(3, "0"));

		return {
			started: true,
			ended: false,
			remain: ms,
			days: dd,
			hours: HH,
			minutes: mm,
			seconds: ss,
			milliseconds: SSS,
			formatTime,
			status: props.name + status
		};
	}

	// 清除定时器
	onUnmounted(() => {
		if (timeoutId) {
		    clearTimeout(timeoutId);
		}
	});
	
</script>

<style lang="scss" scoped>
	.xl-count-down{
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: v-bind(color);
		.time{
			font-size: var(--time-size);
		}
		.cart{
			/* #ifndef APP-PLUS-NVUE */
			display: flex;
			/* #endif */
			flex-direction: row;
			justify-content: center;
			align-items: center;
			font-size: var(--time-size);
			.num{
				background: v-bind(color);
				border-radius: 4rpx;
				color: #fff;
				width: var(--cart-size);
				height: var(--cart-size);
				line-height: var(--cart-size);
				text-align: center;
			}
			.split{
				margin: 0 6rpx;
			}
		}
		.status{
			margin-top: 4rpx;
		}
	}
	
</style>